package br.com.lambdacore.lang;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;

import org.apache.commons.lang.builder.ToStringStyle;

import br.com.lambdacore.lang.annotation.ToString;
import br.com.lambdacore.lang.reflect.AnnotationUtils;

public class ToStringBuilder extends
		org.apache.commons.lang.builder.ToStringBuilder {

	public ToStringBuilder(Object thiz) {
		super(thiz);
		this.appendToString(thiz);
	}

	public ToStringBuilder(Object thiz, ToStringStyle style) {
		super(thiz, style);
		this.appendToString(thiz);
	}

	@SuppressWarnings("unchecked")
	private void appendToString(Object thiz) {
		try {
			Collection<Field> fields = AnnotationUtils.getAllFieldsAnnoted(thiz
					.getClass(), ToString.class);
			for (Field field : fields) {
				field.setAccessible(true);
				this.append(field.getName(), field.get(thiz));
			}
			Collection<Method> methods = AnnotationUtils.getAllMethodsAnnoted(
					thiz.getClass(), ToString.class);
			for (Method method : methods) {
				method.setAccessible(true);
				ToString toString = method.getAnnotation(ToString.class);
				String name = (!toString.value().equals("")) ? toString.value()
						: method.getName().replace("get", "").toLowerCase();
				this.append(name, method.invoke(thiz));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static ToStringBuilder newInstance(Object thiz) {
		return new ToStringBuilder(thiz);
	}

	public static ToStringBuilder newInstance(Object thiz, ToStringStyle style) {
		return new ToStringBuilder(thiz, style);
	}

}
